package cn.wolfcode.crm.realm;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.serivce.IEmployeeService;
import cn.wolfcode.crm.serivce.IPermissionService;
import cn.wolfcode.crm.serivce.IRoleService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Arrays;
import java.util.List;

public class MyRealm extends AuthorizingRealm {
    @Autowired
    IEmployeeService service;
    //查询权限
    @Autowired
    IPermissionService permissionService;
    //查询角色
    @Autowired
    IRoleService roleService;

    //创建方法返回当前数据源名称
    private String getRealmName(){
        return "MyRealm";
    }
    /**
     * 认证:
     * @param  token
     * @return
     * @throws AuthenticationException
     */
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //准备数据库的账号信息
        Employee employee = service.slelectByUsernameInfo((String) token.getPrincipal());
        //判断令牌的用户名是否存在在数据库中,如果存在返回认证信息对象,
        if (employee != null) {
            //参数: 用户名 密码 ,realm的名字
            return new SimpleAuthenticationInfo(employee,employee.getPassword(), ByteSource.Util.bytes(employee.getUsername()),"MyRealm");
        }
        //如果不存在返回null
        return null;
    }
    /**
     * 授权
     * @param  principalCollection
     * @return
     */
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        //获取当前登录用户
        Employee emp =(Employee) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //判断当前用户是否是admin
        if (emp.getAdmin()) {
            //设置超级管理员橘色
            info.addRole("ADMIN");
            //超级管理员可以获取所有的权限
            info.addStringPermission("*:*");
        }else{
            //查询当前用户的角色集合
            List<String> roles = roleService.selectNameByEmployeeId(emp.getId());
            //查询当前员工的权限集合
            List<String> permissions =permissionService.selectNameByEmployeeId(emp.getId());

            info.addRoles(roles);
            info.addStringPermissions(permissions);
        }
        return info;
    }


}
